<?php
class User
{
    /**
     * @var object Zend DB Adapter
     */
    private $_db;
    /**
     * @var string
     */
   
    public function __construct()
    {
		$this->_db = Zend_Registry::get('db');
    }
	
	public function getModules()
	{
		if ($handle = opendir('../application/admin/controllers')) {
			/* This is the correct way to loop over the directory. */
			while (false !== ($file = readdir($handle))) {
				if ($file != "." && $file != "..") {					
					$file_array = explode('.', $file);
					$filename = $file_array[0];					
					$filename = preg_replace("(Controller)", '', $filename);
					//$filename = preg_replace("(Index)", '', $filename);					
					$modules[] = $filename;
					sort($modules);										
				}
			}

			closedir($handle);
		}
		//unset($modules[0]);
		
		return $modules;
	}
	
	public function viewUsers()
	{
		//$user_level = Zend_Auth::getInstance()->getStorage()->read()->id_member;
		$getUsers = $this->_db->fetchAll("
			SELECT userid, first_name, last_name, username, password, email_address, created_date, is_online, status, userlevel
			FROM user
			WHERE userlevel != 'superadmin'
		");
		
		return $getUsers;
	}
	
	public function viewBSEUsers()
	{
		$getBseUsers = $this->_db->fetchAll("
			SELECT userid, first_name, last_name, username, password, email_address, created_date, is_online, status
			FROM user
			WHERE userlevel = 'bse'
		");
		
		return $getBseUsers;
	}
	
	public function viewPLUsers()
	{
		$getPlUsers = $this->_db->fetchAll("
			SELECT userid, first_name, last_name, username, password, email_address, created_date, is_online, status
			FROM user
			WHERE userlevel = 'pl'
		");
		
		return $getPlUsers;
	}
	
	public function viewDEVUsers()
	{
		$getDevUsers = $this->_db->fetchAll("
			SELECT userid, first_name, last_name, username, password, email_address, created_date, is_online, status
			FROM user
			WHERE userlevel = 'dev'
		");
		
		return $getDevUsers;
	}
	
	public function addUser($form_values)
	{
		$firstname = $form_values['firstname'];
		$lastname = $form_values['lastname']; 
		$email = $form_values['email'];
		$username = $form_values['username']; 
		$password = md5($form_values['password']);	
		$user_type = $form_values['userlevel'];
		$status = $form_values['status'];
		
		$add_user = $this->_db->exec(
			"INSERT INTO user(first_name, last_name, email_address, username, password, created_date, userlevel, status, is_online)
			 VALUES('" . $firstname . "', '" . $lastname . "', '" . $email . "', '" . $username . "', '" . $password . "', now(), '" . $user_type . "', " . $status . ", 0)
			");
		  
        if($add_user)
        {
        	echo "New user has been successfully created";
        }
	}
	
	public function viewUsersById($userid)
	{
		
		$getUsers = $this->_db->fetchRow("
			SELECT U.userid, U.first_name, U.last_name, U.username, U.password, U.email_address, U.created_date, U.is_online, U.userlevel, U.status
			FROM user AS U
			WHERE U.userid = '" . $userid . "' AND U.userlevel != 'superadmin'
		");
		
		/*$getUsers = $this->_db->fetchAll("
			SELECT U.first_name, U.last_name, U.username, U.password, U.email_address, U.created_date, U.is_online, U.status
			FROM USER AS U	
			INNER JOIN event_sub_user SU ON SU.user_id = U.userid
			WHERE U.userlevel != 'superadmin'
		");*/
		
		return $getUsers;
	}
	
	public function getUserPermission()
	{
		$getPermission = $this->_db->fetchAll("
			SELECT P.user_type, P.module, P.acl
			FROM permission AS P			
		");
		
		return $getPermission;
	}
	
	public function updateUser($form_values)
	{
		$userid = $form_values['userid'];
		$firstname = $form_values['firstname'];
		$lastname = $form_values['lastname']; 
		$email = $form_values['email'];
		$user_type = $form_values['userlevel'];
		$status = $form_values['status'];
		try {
			$update_user = $this->_db->query("
				UPDATE user
				SET first_name = '" . $firstname . "', last_name = '" . $lastname . "', email_address = '" . $email . "', created_date = now(), userlevel = '" . $user_type . "', status = '" . $status . "'
				WHERE userid = " . $userid . "
			");
			if($update_user) {
			    echo "User details has been successfully updated";
			}
		} catch (Exception $e) {
			return false;
		}
			
	}
	
	public function deleteUser($userid)
	{
		$delUser = $this->_db->query("
                    DELETE FROM user
                	WHERE userid = " . $userid . "
                   ");
    	if($delUser)
        {
            echo "Selected user has been successfully deleted";
        }
	}
	
	public function getUserPermissionByType($usertype)
	{
		$userPermission = $this->_db->fetchAll("
			SELECT module, acl
			FROM permission
			WHERE user_type = '" . $usertype . "'
		");
		
		return $userPermission;
	}
	
	public function createRandomPassword() 
	{
	    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double)microtime()*1000000);
        $i = 0;
        $pass = '' ;
        while ($i <= 7) 
        {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }
    
    public function resetPassword($username)
    {
        $random_password = $this->createRandomPassword();
        $reset_password = $this->_db->query("
            UPDATE user 
            SET password = md5('" . $random_password . "')
            WHERE username = '" . $username . "'
        ");
        
        if($reset_password)
        {
            echo $username . "-" . $random_password;
        }
    }
    
    public function updateAdminPassword($userid, $curr_pwd, $new_pwd)
    {
        $user_arr = $this->_db->fetchRow("
            SELECT userlevel
            FROM user
            WHERE userid = " . $userid
        );
        
        $userlevel = $user_arr['userlevel'];
        $curr_pwd = md5($curr_pwd);
        $new_pwd = md5($new_pwd);
        
        $reset_password = $this->_db->query("
            UPDATE user 
            SET password = '" . $new_pwd . "'
            WHERE userid = " . $userid . " AND userlevel = '" . $userlevel . "'
        ");
        
        if($reset_password)
        {
            echo "Your Password has been changed";
        }
    }
    
    public function updateUserProfile($form_values)
    {
    	$userid = $form_values['userid'];
		$firstname = $form_values['first_name'];
		$lastname = $form_values['last_name']; 
		$email = $form_values['email'];

		try {
			$update_user = $this->_db->query("
				UPDATE user
				SET first_name = '" . $firstname . "', last_name = '" . $lastname . "', email_address = '" . $email . "', created_date = now()
				WHERE userid = " . $userid . "
			");
			if($update_user) {
			    echo "You have changed your current profile. Please re-login for the changes to take effect";
			}
		} catch (Exception $e) {
			return false;
		}	
    }
    
    public function getProfileImage($userid)
    {
    	$profile_img = $this->_db->fetchRow("
    		SELECT profile_image 
    		FROM profile_image
    		WHERE user_id = " . $userid);
    	
    	return $profile_img;
    }
    
    public function getThemeImage($userid)
    {
    	$themes_img = $this->_db->fetchRow("
    		SELECT filename
    		FROM themes
    		WHERE userid = " . $userid);
    	
    	return $themes_img;
    }
    
    public function delProfileImage($userid)
    {
    	$profile_image = $this->getProfileImage($userid);
    	unlink("images/profileimg/thumbs/" . $profile_image['profile_image']);
    	unlink("images/profileimg/large/" . $profile_image['profile_image']);
    	$del_profile_img = $this->_db->exec("
	    			DELETE FROM profile_image
	    			WHERE user_id = " . $userid);
    }
    
    public function delThemeImage($userid)
    {
    	$theme_image = $this->getThemeImage($userid);
    	unlink("images/themeimage/" . $theme_image['filename']);
    	$del_theme_img = $this->_db->exec("
	    			DELETE FROM themes
	    			WHERE userid = " . $userid);
    }
    
    public function addProfileImage($filename, $userid)
    {
    	$have_image = $this->getProfileImage($userid);
    	if($have_image)
    	{
    		$del_profile_img = $this->delProfileImage($userid);
    		$add_profile_img = $this->_db->exec(
    				"INSERT INTO profile_image(user_id, profile_image) 
    		 		VALUES(" . $userid . ", '" . $filename . "')");	
    	} else {    	
    		$add_profile_img = $this->_db->exec(
    			"INSERT INTO profile_image(user_id, profile_image) 
    		 	VALUES(" . $userid . ", '" . $filename . "')");
    	}		 
    }
    
    public function updatePassword($userid, $curr_pass, $new_pass)
    {
    	$chk_pass = $this->_db->fetchRow("
    		SELECT COUNT(*) AS RECCOUNT
    		FROM user
    		WHERE userid = " . $userid . " AND password = '" . $curr_pass . "' 
    	");
    	
    	if($chk_pass['RECCOUNT'] == 0)
    	{
    		echo "invpass";
    	} else {    	
	    	$update_pass = $this->_db->exec("
	    		UPDATE user SET password = '" . $new_pass . "' 
	    		WHERE userid = " . $userid);
	    	if($update_pass)
	    	{
	    		echo "You have changed your current password. Please re-login for the changes to take effect";
	    	}
	    	
    	}
    }
    
    public function updateStatusLogin($userid)
    {
    	$this->_db->exec("
    		UPDATE user 
    		SET is_online = 1
    		WHERE userid = " . $userid);
    }
    
    public function updateStatusLogout($userid)
    {
    	$this->_db->exec("
    		UPDATE user 
    		SET is_online = 0
    		WHERE userid = " . $userid);
    }
    
    public function getMemberCount()
    {
    	$mem_count_arr = $this->_db->fetchRow("
    		SELECT COUNT(userid) AS MEMCOUNT
    		FROM user
    		WHERE userlevel != 'superadmin'
    	");
    	
    	return $mem_count_arr;
    }
    
    public function getUserStats()
    {
    	$user_stat_arr = $this->_db->fetchRow("
    		SELECT COUNT(userid) AS LIVEUSERS
    		FROM user
    		WHERE is_online = 1 
    		AND userlevel != 'superadmin'
    	");
    	
    	return $user_stat_arr;
    }
    
    public function getLiveUsers()
    {
    	$user_arr = $this->_db->fetchAll("
    		SELECT userid, first_name, last_name
    		FROM user
    		WHERE is_online = 1 
    		AND userlevel != 'superadmin'
    	");
    	
    	return $user_arr;
    }
    
    public function getUserCustomerInfoByUserId($userid)
    {
    	$arr = $this->_db->fetchAll("
    		SELECT P.project_title
			FROM projects P
			LEFT JOIN customer C ON C.customer_id = P.customer_id
			LEFT JOIN USER U ON U.userid = P.bse_id
			WHERE U.userid = " . $userid);
    	
    	return $arr;
    }
    
    public function getProjectLeader($userid)
    {
    	$arr = $this->_db->fetchAll("
    		SELECT U.first_name, U.last_name
			FROM USER U
			LEFT JOIN projects P ON U.userid = P.pl_id
			WHERE P.pl_id IN (SELECT P.pl_id FROM projects P WHERE P.bse_id = " . $userid . ")
			GROUP BY U.userid 
    	");
    	
    	return $arr;
    }
    
    public function getPLGroupMembers($pl_id)
    {
    	$arr = $this->_db->fetchAll("
    		SELECT P.bse_id, U.first_name, U.last_name
			FROM USER U
			LEFT JOIN projects P ON U.userid = P.bse_id
			WHERE P.pl_id = " . $pl_id);
    	
    	return $arr;
    }
    
    public function resetPasswordByEmail($form_values)
    {
        $user_email = $form_values['email'];
        $user_passwd = $form_values['userpasswd'];
    	
    	$reset_password = $this->_db->exec("
            UPDATE user 
            SET password = md5('" . $user_passwd . "')
            WHERE email_address = '" . $user_email . "'
        ");
        
        if($reset_password)
        {
            echo "Password has been successfully changed. You can change your password anytime by edit your profile details.";
        }
    }
    
    public function addThemeImage($filename, $userid) 
    {
    	$have_theme = $this->getThemeImage($userid);
    	if($have_theme)
    	{
    		$del_theme_img = $this->delThemeImage($userid);
    		$add_theme_img = $this->_db->exec(
    				"INSERT INTO themes(userid, filename) 
    		 		VALUES(" . $userid . ", '" . $filename . "')");	
    	} else {    	
    		$add_theme_img = $this->_db->exec(
    			"INSERT INTO themes(userid, filename) 
    		 	VALUES(" . $userid . ", '" . $filename . "')");	
    	}
    }
    
    public function getUsersToAddEvent($curr_userid) 
    {
    	$user_arr = $this->_db->fetchAll("
    		SELECT userid, first_name, last_name, username, userlevel
    		FROM user
    		WHERE userid != " . $curr_userid . " 
    		AND userlevel = 'bse'
    		OR userlevel = 'pl'
    		AND status = 1" 
    	);
    	
    	return $user_arr;
    }
}